﻿using System;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Linq;
using System.Web;

using Com.Ompchina.Lib.Net;
using Com.Ompchina.Lib.Text;
using Model.AuthModel;
using BLL.AuthModel;
using Util.Helper;
using UI.WebPage.PageBase;
namespace Com.Ompchina.Web.admin.WebHandlers.user
{
    public class login : AshxBase, IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string username =context.Server.HtmlEncode(RequestParam.GetString(context.Request, "username"));
            string password = RequestParam.GetString(context.Request, "password");
            if (string.IsNullOrEmpty(username))
                Repo = string.Format(Format[0], 0, "请输入用户名");
            else
            {
                StaffInfo info = this.GetStaffByUsername(username);                
                if (this.CheckStaff(info, password))
                {
                    ///登录记录保存成功才能进入，避免数据误差
                    if (new StaffLoginBLL().InsertStaffLogin(info, context.Request.UserHostAddress)) 
                    {
                        new StaffHelper().SetLoginStaff(context, info);
                        Repo = string.Format(Format[0], 1, "登录成功，欢迎回来：" + info.Username);
                    }
                    else
                        Repo = string.Format(Format[0], 0, "登录错误，请稍后再试");
                }
                else
                    Repo = string.Format(Format[0], 0, Message);
            }
            context.Response.Write(Repo);
        }

        #region 私有方法
        /// <summary>
        /// 根据用户名获取成员信息
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private StaffInfo GetStaffByUsername(string userName)
        {            
            return new StaffBLL().StaffLogin(userName);
        }

        private bool CheckStaff(StaffInfo info, string password) 
        {            
            if (info.StaffID == 0) 
            {
                Message = "管理员不存在";
                return false;
            }
            else if (!info.Password.Equals(Security.MD5(password))) 
            {
                Message = "登录密码错误";
                return false;
            }
            else if (info.IsLock.Equals("y")) 
            {
                Message = "您的帐号为锁定状态，不能登录";
                return false;
            }
            return true;
        }
        #endregion
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
